# This module provides helper functions for the xml_item_submit view that parse XML data in POST requests and updates item statistics from an item instance.

# A generic XML request body should look like this:
# 
# <entity kind="item_instance">
#   <property name="itemname" type="null">Generic Item</property>
#   ...
#   <property name="effects" type="null>
#     <effect>GLOW</effect>  
#     <effect>BLESS</effect>  <==== Element name doesn't matter for procedure.
#   </property>
#   ...
# </entity>
from items.models import item_instance
from django.http import HttpResponse
from xml.etree.ElementTree import *

def process_xml_item(request):
    
    new_item_inst = item_instance()

    # We use the properties dictionary to validate XML element names.

    item_inst_props = new_item_inst.properties()
    inst_xml_data = XML(request.raw_post_data)

    # Iterate over every child element in the XML request and make sure
    # the 'name' attributes match attributes names on our model. 

    for inst_xml_element in inst_xml_data.getchildren():

        # Determine if the element is a list, numeric, or just a string.
        if len(inst_xml_element.getchildren()) != 0:
            value = make_list(inst_xml_element.getchildren())
        elif inst_xml_element.text != None and inst_xml_element.text.isdigit():
            value = int(inst_xml_element.text)
        else:
            value = inst_xml_element.text

        # Copy the newly formatted value from XML to our model instance.

        element_name = inst_xml_element.attrib['name']
        if item_inst_props.has_key(element_name):
            new_item_inst.__setattr__(element_name, value)
        
    return new_item_inst

def make_list(xml_list):
    list = []
    for element in xml_list:
        list.append(element.text)
    return list

def update_statistics(current_item_def, new_item_instance):

    collection_list = ['level',
                       'ac',
                       'dr',
                       'hr',
                       'hp',
                       'mana',
                       'sbr',
                       'ss',
                       'srod',
                       'spar']

    item_properties = new_item_instance.properties()
    item_def_properties = current_item_def.properties()

    for attr in item_properties.keys():
        if attr in collection_list:
            attr_value = new_item_instance.__getattribute__(attr)
            if attr_value != None and attr_value != []:
                avgattr = 'avg' + attr
                minattr = 'min' + attr
                maxattr = 'max' + attr
                
                if current_item_def.num_insts != None:
                    current_item_def.num_insts += 1 #Increment sample size first
                else:
                    current_item_def.num_insts = 1
                oldavg = current_item_def.__getattribute__(avgattr)
                if oldavg != None:
                    # next line works because we updated the sample size first
                    newavg = oldavg - (attr_value - oldavg)/(current_item_def.num_insts)
                else:
                    newavg = attr_value
                current_item_def.__setattr__(avgattr, newavg)
                
                oldmin = current_item_def.__getattribute__(minattr)
                oldmax = current_item_def.__getattribute__(maxattr)
                if oldmin != None and oldmax != None:
                    if attr_value < oldmin:
                        current_item_def.__setattr__(minattr, attr_value)    
                    elif attr_value > oldmax:
                        current_item_def.__setattr__(maxattr, attr_value)
                else:
                    current_item_def.__setattr__(minattr, attr_value)
                    current_item_def.__setattr__(maxattr, attr_value)
                    
                    
    
    
